package com.servlet.article;

import com.entity.Article;
import com.entity.Code;
import com.service.ArticleService;
import com.utils.JsonUtil;
import com.utils.TimeString;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

import java.io.IOException;

/**
 * 发布文章
 * 必添参数  title  author  context
 * 可选参数 tag
 */
@WebServlet("/addArticle")
public class AddArticle extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        JsonUtil jsonUtil = new JsonUtil();
        ArticleService articleService = new ArticleService();
        Article article = new Article();
        article.setArt_title(request.getParameter("title"));
        article.setArt_author(request.getParameter("author"));
        article.setArt_context(request.getParameter("context"));
        article.setArt_tag(request.getParameter("tag"));
        article.setArt_create_time(new TimeString().TimeString());
        try {
            if (article.getArt_title()==""||article.getArt_author()==""|| article.getArt_context()==""){
                Code code = new Code();
                code.setMsg("标题、作者、内容为必填项");
                code.setCode("403");
                String s = jsonUtil.JavaToJson(code);
                response.getWriter().print(s);
            }else {
                articleService.addArticle(article);
                Code code = new Code();
                code.setCode("200");
                code.setMsg("文章发布成功");
                String s = jsonUtil.JavaToJson(code);
                response.getWriter().print(s);
            }

        }catch (Exception e){
            System.out.println("添加文章出错:"+e);
            Code code = new Code();
            code.setMsg("添加文章失败，请稍后再试");
            code.setCode("404");

            String s = jsonUtil.JavaToJson(code);
            response.getWriter().print(s);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
